# coding = UTF-8
# @Time : 2022/05/07 20:15
# @Author : PP_YY
# @File : 实验2.py
# @Description : 解析网页输出网页源码和中文内容
import re  # 正则表达式模块import re #正则表达式模块
from bs4 import BeautifulSoup  # 进行数据获取，网页解析
import urllib.request, urllib.parse  # 指定url获取数据
import tkinter

findChinese = re.compile(r'[\u4e00-\u9fa5]+') # 找汉字

top = tkinter.Tk()
top.title("网页解析")
top.geometry('800x600')
top.resizable(0, 0)
entry_string = tkinter.Entry(top, bd=1,width=50)
text1 = tkinter.Text(top,bd=0,font=('等线', 12),highlightthickness=0,width=90,height=10)
text2 = tkinter.Text(top,bd=0,font=('等线', 12),highlightthickness=0,width=90,height=10)

def getData(_baseurl):
    datalist = []
    url = _baseurl
    html = askurl(url)
    soup = BeautifulSoup(html, "html.parser")

    soup = str(soup)
    datalist = re.findall(findChinese,soup)
    return soup, datalist


def askurl(url):
    head = {
        "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/79.0.3945.147 Safari/534.24 Device/elish Model/M2105K81AC XiaoMi/MiuiBrowser/14.6.50"}
    request_t = urllib.request.Request(url, headers=head)
    try:
        html = urllib.request.urlopen(request_t)
    except urllib.error.URLError as e1:
        print(e1)
    except urllib.error.HTTPError as e2:
        print(e2)
    # print(html.read().decode())
    return (html)

def main():
    global entry_string,top,text1,text2
    label1 = tkinter.Label(top, text='HTML源码: ', width=15, font=("等线", 9),fg='blue')
    label1.place(x=10, y=80)
    label2 = tkinter.Label(top, text= '解析内容: ', width=15, font=("等线", 9),fg ='blue')
    label2.place(x=5, y=310)

    baseurl = entry_string.get()
    soup, datalist = getData(baseurl)
    soup = str(soup)
    datalist_str = "\n".join(datalist)

    text1.insert('1.0',soup)
    text1.config(state="disable")
    text2.insert('1.0', datalist_str)
    text2.config(state="disable")
    

def GUI_main():
    global entry_string,top,show_data
    notice_label = tkinter.Label(top, text="请输入需要解析的网页", width=40, font=('等线', 15))
    start_button = tkinter.Button(top, text="解析", command=main, bd=1, font=('等线', 15))
    entry_string.place(x=15, y=40)
    start_button.place(x=360, y=31)
    notice_label.place(x=-118, y=10)
    text1.place(x=20,y=95)
    text2.place(x=20,y=330)
    top.mainloop()


if __name__ == "__main__":
   
    GUI_main()
